/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * <pre>
 * Copyright (C) 2004-2009 Giant Interective Group, Inc. All rights reserved.
 * 版权所有 2004-2009 上海巨人网络科技有限公司
 * </pre>
 *
 * @version #version, #date
 * @author  Zhangkai
 * Depend on jQuery 1.3.x
 */
if (typeof giant === 'undefined')
    var giant = {};

if (typeof giant.ui === 'undefined')
    giant.ui = {};
(function($) {
    /**
     * 创建个新的giant.ui.autocomplete实例。
     * @giant.ui.autocomplete实例 相册组件。
     * @constructor
     * @param {object}
            * @param {function}回调函数
            * @returns {giant.ui.autocomplete}实例
     * @example
     *<pre>
     * //以下代码放在body里
     * &lt;div class=&quot;ml10 pd15 prel&quot;&gt;
     *       &lt;input type=&quot;text&quot; class=&quot;txt w240&quot; id=&quot;ui-autocomplete-input&quot; value=&quot;Tony&quot; /&gt;
     * &lt;button class=&quot;btn-small blue&quot; type=&quot;button&quot;&gt;搜 人&lt;/button&gt;
     *        &lt;div class=&quot;txt-list&quot; id=&quot;ui-autocomplete-result&quot;&gt;
     *        &lt;/div&gt;
     * &lt;/div&gt;
     * //以下代码放在body的onload函数里
     *  $(document).ready(function(){
     *  var auto = new giant.ui.autocomplete({ajaxUrl:"test.asp"},function(str){
     *      alert("搜索"+str)
     *  });
     *});
     * </pre>
     */
    var _timeout = null;
    giant.ui.autocomplete = function(options, callBack) {
        this.callBack = callBack || null;
        this.opts = $.extend({}, giant.ui.autocomplete.defaults, options);
        this.isResultShow = false;
        this.result = null;
        this.activeIndex = -1;
        this._init();
    };
    giant.ui.autocomplete.prototype = {
        _init:function() {
            this._setPostion();
            this._keyUpBind();
            this._clickBind();
        },
        _setPostion:function() {
            var $this = this;
            $(this.opts.result).width($(this.opts.input).innerWidth());
            $(this.opts.result).css({"top":$($this.opts.input).position().top + $(this.opts.input).outerHeight() + "px","left":$($this.opts.input).position().left + "px"});
        },
        _clickBind:function() {
            var $this = this;
            $(document).bind("mousedown", function(event) {
                if ($(event.target).parents($this.opts.result).size() == 0) {
                    setTimeout(function() {
                        $this.setResultHide();
                    }, 100);
                }
            });
        },
        _keyUpBind:function() {
            var $this = this;
            $(this.opts.input).bind("keyup", function(event) {
                if (event.keyCode != "40" && event.keyCode != "38" && event.keyCode != "39" && event.keyCode != "37" && event.keyCode != "13") {
                    $this.activeIndex = -1;
                    if ($($this.opts.input).val().length > 0) {
                        if (_timeout != null) {
                            clearTimeout(_timeout);
                        }
                        _timeout = setTimeout(function() {
                            $.ajax({
                                type:"POST",
                                url:$this.opts.ajaxUrl,
                                data:"name=" + $($this.opts.input).val(),
                                success:function(msg) {
                                    var data = eval("(" + msg + ")");
                                    if (data.status == -1) {
                                        $this.setResultHide();
                                        return;
                                    }
                                    if (!$this.isResultShow) {
                                        $this.setResultShow();
                                    }
                                    var arr = [];
                                    arr.push()
                                    $.each(data, function(i, n) {
                                        arr.push("<a href='javascript:void(0)'>" + n + "</a>");
                                    });
                                    $($this.opts.result).html(arr.join(''));
                                    $($this.opts.result).find("a").each(function(index) {
                                        $(this).unbind("click").bind("click", function() {
                                            $($this.opts.input).val($(this).text());
                                            $this.result = $(this).text();
                                            setTimeout(function() {
                                                $this.setResultHide();
                                            }, 100);
                                            if ($this.callBack) {
                                                $this.callBack($this.result);
                                            }
                                        });
                                        $(this).unbind("mouseover").bind("mouseover", function() {
                                            $this.activeIndex = index;
                                            $($this.opts.result).find("a").removeClass("active");
                                            $($this.opts.result).find("a").eq($this.activeIndex).addClass("active");
                                        });
                                    });
                                }
                            });
                        }, 50);
                    } else {  //若为空
                        $this.setResultHide();
                    }
                }
                if ($this.isResultShow) {
                    var totalCount = $($this.opts.result).find("a").size();
                    if (totalCount > 0) {
                        //down 键
                        switch (event.keyCode) {
                            case 40:
                                if ($this.activeIndex < totalCount - 1) $this.activeIndex++;
                                else  $this.activeIndex = 0;
                                break;
                            case 38:
                                if ($this.activeIndex > 0)  $this.activeIndex--;
                                else  $this.activeIndex = totalCount - 1;
                                break;
                        }
                        $($this.opts.result).find("a").removeClass("active");
                        if ($this.activeIndex >= 0) {
                            $($this.opts.result).find("a").eq($this.activeIndex).addClass("active");
                            $this.result = $($this.opts.result).find("a.active").text();
                            $($this.opts.input).val($this.result);
                        }
                    }
                }
                if (event.keyCode == 13 && $this.callBack) {
                    $this.callBack($($this.opts.input).val());
                    setTimeout(function() {
                        $this.setResultHide();
                    }, 100);
                }
            });
        },
        /**
         * 设置推荐列表为显示
         */
        setResultShow:function() {
            this._setPostion();
            this.isResultShow = true;
            $(this.opts.result).show();
        },
        /**
         * 设置推荐列表为隐藏
         */
        setResultHide:function() {
            this.isResultShow = false;
            $(this.opts.result).hide();
            $(this.opts.result).html("");
            this.activeIndex = -1;
        },
        /**
         * 获取选中的结果
         * @return{String} 返回当前文本框的值
         */
        getResult:function() {
            return this.result;
        }
    }
    /**
     * 默认参数<br / >
     * input==>输入框的xpath路径<br />
     * result==>推荐列表的xpath路径<br />
     * ajaxUrl==>提供ajax数据的页面路径
     */
    giant.ui.autocomplete.defaults = {
        input:"#ui-autocomplete-input",
        result:"#ui-autocomplete-result",
        ajaxUrl:""
    };
})(jQuery);